package com.huluobo.high3demo.live;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.high3demo.R;
import com.huluobo.high3demo.adapter.GiftAdapter;
import com.huluobo.high3demo.adapter.MessageAdapter;
import com.huluobo.high3demo.databinding.ActivityLiveBinding;
import com.huluobo.high3demo.entity.MessageEntity;
import com.huluobo.mvvm.baen.FollowLikeBeanResult;
import com.huluobo.mvvm.baen.GiftBeanResult;
import com.huluobo.mvvm.baen.VideoBeanResult;
import com.huluobo.mvvm.db.eneity.Money;
import com.huluobo.mvvm.net.Constant;
import com.huluobo.mvvm.utils.ImageLoader;
import com.huluobo.mvvm.view.BaseMVVMActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {

    private VideoBeanResult.VideoBean videoBean;
    private DanmakuContext dammuContext;

    private final List<GiftBeanResult.GiftBean> giftBeans = new ArrayList<>();

    private GiftAdapter giftAdapter;

    private GiftBeanResult.GiftBean giftBean;

    private Money money;

    private MessageAdapter messageAdapter;
    private final List<MessageEntity> messageEntities = new ArrayList<>();

    @Override
    protected void initData() {
        viewModel.queryUserMoney(SPUtils.getInstance().getString(Constant.SP_USERNAME));
        viewModel.followSuccess.observe(this, new Observer<FollowLikeBeanResult>() {
            @Override
            public void onChanged(FollowLikeBeanResult followLikeBeanResult) {
                ToastUtils.showLong("关注成功");
                //关注状态
                dataBinding.liveBtnFollow.setText("已关注");
                dataBinding.liveBtnFollow.setBackgroundResource(
                        R.drawable.shape_pink);
                videoBean.setGuanzhu(1);
            }
        });

        viewModel.giftSuccess.observe(this, new Observer<GiftBeanResult>() {
            @Override
            public void onChanged(GiftBeanResult giftBeanResult) {
                if (giftBeanResult.getData().size() > 0) {
                    giftBeans.addAll(giftBeanResult.getData());
                    giftAdapter.notifyDataSetChanged();
                }
            }
        });

        //观察用户余额的变化,来赋值
        viewModel.moneySuccess.observe(this, new Observer<Money>() {
            @Override
            public void onChanged(Money money) {
                LiveActivity.this.money = money;
                dataBinding.liveTvUserMoney.setText("余额:" + money.money + "抖币");
            }
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");

        //设置播放器的返回按钮隐藏
        dataBinding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);

        //设置视频地址
        dataBinding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
        dataBinding.liveGsyPlayer.startPlayLogic();

        //设置基本信息
        //头像
        ImageLoader.getInstance().loadCircleImage(this, videoBean.getHeadpath(), dataBinding.liveIvUserIcon);
        //用户名
        dataBinding.liveTvUsername.setText(videoBean.getAuthname());
        dataBinding.liveTvLikeCount.setText(videoBean.getLike_count() / 10000 + "W+ 人点赞");
        //关注状态
        dataBinding.liveBtnFollow.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        dataBinding.liveBtnFollow.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_alphablack :
                R.drawable.shape_pink);
        dataBinding.liveBtnFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followAuth();
            }
        });

        int[] resIds = {
                R.drawable.ic_favorite_0,
                R.drawable.ic_favorite_1,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_5,
                R.drawable.ic_favorite_4,
                R.drawable.ic_favorite_3,
                R.drawable.ic_favorite_2,
                R.drawable.ic_favorite_1
        };
        //添加点赞动画图片
        dataBinding.liveLikeView.setResId(resIds);

        //发送点赞飘心动画
        dataBinding.liveIvLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.liveLikeView.addFavor();
            }
        });

        //点击弹出弹幕输入框布局
        dataBinding.liveIvDanmu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.liveLlDanmuLayout.setVisibility(View.VISIBLE);
            }
        });

        //点击发送弹幕的事件
        dataBinding.liveIvDanmuSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendDanmu();
            }
        });

        //初始化弹幕
        initDanmuView();

        //礼物按钮点击事件
        dataBinding.liveIvGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGiftLayout();
            }
        });

        //礼物关闭按钮点击事件
        dataBinding.liveTvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeGiftList();
            }
        });

        //初始化礼物列表
        dataBinding.liveRvGiftList.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter(giftBeans);
        dataBinding.liveRvGiftList.setAdapter(giftAdapter);

        //礼物列表item的点击事件
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                giftBean = giftBeans.get(position);
                ImageLoader.getInstance().loadCircleImage(LiveActivity.this, giftBean.getGiftpath(),
                        dataBinding.liveIvGiftSelect);
                dataBinding.liveTvGiftName.setText(giftBean.getGiftname());
            }
        });

        //礼物列表发送的点击事件
        dataBinding.liveGiftSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGift();
            }
        });

        //初始化聊天列表
        messageAdapter = new MessageAdapter(messageEntities);
        dataBinding.liveRoomList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.liveRoomList.setAdapter(messageAdapter);

        //初始化环信聊天室
        initChatRoom();

        //消息按钮点击事件
        dataBinding.liveTvInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBinding.liveLlMsgLayout.setVisibility(View.VISIBLE);
            }
        });
        dataBinding.liveIvMsgSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendTextMessage();
            }
        });
    }

    private void sendTextMessage() {
        if (dataBinding.liveEtMsgInput.getText().toString().length() != 0) {
            sendEMRoomMessage(Constant.ROOM_ID, dataBinding.liveEtMsgInput.getText().toString());
        } else {
            ToastUtils.showLong("请输入聊天内容");
        }
    }

    private void initChatRoom() {
        EMClient.getInstance().chatroomManager().joinChatRoom(Constant.ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                Log.i("TagA","聊天室初始化成功");
                //添加聊天室的监听器
                EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
                //添加消息的监听器
                EMClient.getInstance().chatManager().addMessageListener(messageListener);
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "初始化聊天室失败:" + errorMsg + ",code:" + error);
            }
        });
    }

    private final EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //需要将接受到的消息添加到聊天室列表,刷新适配器
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //遍历集合,封装消息实体
                    for (EMMessage message : messages) {
                        String fromName = message.getFrom();//拿到消息发送的用户名
                        EMTextMessageBody messageBody = (EMTextMessageBody) message.getBody();//EMMessage
                        // 中没办法直接拿到消息内容,需要拿到body然后转化
                        String content = messageBody.getMessage();
                        if (content.length() > 6) {
                            String system = content.substring(content.length() - 6, content.length());
                            if (system.equals("进入直播间了") || system.equals("退出直播间了")) {
                                fromName = "系统";
                            }
                        }
                        //封装消息
                        MessageEntity messageEntity = new MessageEntity(fromName, content);
                        //聊天消息的数据源中加入bean
                        messageEntities.add(messageEntity);
                        //刷新聊天室适配器,展示接收到的消息
                        messageAdapter.notifyDataSetChanged();
                        //滚动到最新消息的位置
                        dataBinding.liveRoomList.scrollToPosition(messageEntities.size() - 1);
                    }
                }
            });
        }
    };

    private final EMChatRoomChangeListener chatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            //当用户进入直播间时,发送一条消息,比如:张三:进入聊天室了,舰长进入聊天室
            //通过环信发送一条消息,
            sendEMRoomMessage(Constant.ROOM_ID, participant + "进入直播间了");
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            sendEMRoomMessage(Constant.ROOM_ID, participant + "退出直播间了");
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    //往聊天室发送一条消息
    private void sendEMRoomMessage(String roomId, String content) {
        EMMessage emMessage = EMMessage.createTextSendMessage(content, roomId);
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);
        emMessage.setBody(new EMTextMessageBody(content));
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("TagA", "发送消息成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String fromName = EMClient.getInstance().getCurrentUser();
                        if (content.length() > 6) {
                            String system = content.substring(content.length() - 6, content.length());
                            if (system.equals("进入直播间了") || system.equals("退出直播间了")) {
                                fromName = "系统";
                            }
                        }
                        MessageEntity message = new MessageEntity(fromName, content);
                        messageEntities.add(message);
                        messageAdapter.notifyDataSetChanged();
                        dataBinding.liveRoomList.scrollToPosition(messageEntities.size() - 1);
                        dataBinding.liveEtMsgInput.setText("");
                        dataBinding.liveLlMsgLayout.setVisibility(View.GONE);
                    }
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.i("TagA", "发送消息失败:" + error + ",code:" + code);
            }
        });
    }

    private void sendGift() {
        //拿到用户余额
        //扣款的逻辑(账号余额不足->充值,余额足够-> 扣款,更新UI,更新账号余额)
        if (giftBean == null || money == null) {
            return;
        }

        if (money.money < giftBean.getPrice()) {
            ToastUtils.showLong("用户余额不足,请充值");
            return;
        }

        float newMoney = money.money - giftBean.getPrice();
        //更新UI上的余额
        dataBinding.liveTvUserMoney.setText("余额:" + newMoney + "抖币");
        //更新数据库中的余额
        money.money = newMoney;
        viewModel.updateUserMoney(money);


        //定义礼物动画
        ImageView giftAnimView = new ImageView(this);
        //new出的view都需要设置宽高,但是,宽高并不能直接给view来设置,需要使用Layout的LayoutParams来设置
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftAnimView.setLayoutParams(params);
        //把创建好的imageView添加到布局上
        dataBinding.liveClRoot.addView(giftAnimView);
        //给image添加图片资源
        ImageLoader.getInstance().loadImage(this, giftBean.getGiftpath(), giftAnimView);

        //展示礼物动画
        int screenWidth = dataBinding.liveClRoot.getMeasuredWidth();//获取根布局的宽高
        int screenHeight = dataBinding.liveClRoot.getMeasuredHeight();

        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftAnimView, "TranslationY", screenHeight,
                screenHeight / 3, screenHeight / 2);
        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftAnimView, "TranslationX", screenWidth / 2,
                screenWidth / 3 * 2, screenWidth / 2, screenWidth / 3, screenWidth / 2);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftAnimView, "Rotation", 0, 1080);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftAnimView, "ScaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftAnimView, "ScaleY", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftAnimView, "Alpha", 0.1f, 0.5f, 1.0f, 0.5f, 0.f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(3000);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.playTogether(translationX, translationY, rotation, scaleY, scaleX, alpha);

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                dataBinding.liveClRoot.removeView(giftAnimView);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                dataBinding.liveClGiftLayout.setVisibility(View.GONE);
            }
        });
        animatorSet.start();


    }

    private void closeGiftList() {
        dataBinding.liveClGiftLayout.setVisibility(View.GONE);
    }

    private void openGiftLayout() {

        giftBeans.clear();
        dataBinding.liveClGiftLayout.setVisibility(View.VISIBLE);
        viewModel.getGiftList();
    }

    private void initDanmuView() {
        //1.清理弹幕缓存
        dataBinding.liveDanmuView.enableDanmakuDrawingCache(false);
        dataBinding.liveDanmuView.clear();
        dataBinding.liveDanmuView.removeAllDanmakus(true);

        //2.创建弹幕的上下文
        dammuContext = DanmakuContext.create();

        //3.准备弹幕
        dataBinding.liveDanmuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, dammuContext);
    }

    private void sendDanmu() {
        //获取弹幕内容
        String danmuString = dataBinding.liveEtDanmuInput.getText().toString();
        if (TextUtils.isEmpty(danmuString)) {
            ToastUtils.showLong("请输入弹幕内容");
            return;
        }

        //清理弹幕
        dataBinding.liveDanmuView.clear();
        dataBinding.liveDanmuView.removeAllDanmakus(true);

        //创建弹幕的实体
        BaseDanmaku danmaku = dammuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL); //设置方向从右到左
        danmaku.text = danmuString;//设置弹幕内容
        danmaku.textSize = 30;
        danmaku.textColor = Color.WHITE;
        danmaku.padding = 10;
        danmaku.setTime(800);

        //添加弹幕到视图中
        dataBinding.liveDanmuView.addDanmaku(danmaku);
        dataBinding.liveDanmuView.start();

        //清理输入框和隐藏输入框布局
        dataBinding.liveDanmuView.postDelayed(new Runnable() {
            @Override
            public void run() {
                dataBinding.liveEtDanmuInput.setText("");
                dataBinding.liveLlDanmuLayout.setVisibility(View.GONE);
            }
        }, 300);
    }

    private void followAuth() {
        if (videoBean.getGuanzhu() != 0) {
            ToastUtils.showLong("已经关注过啦");
            return;
        }
        viewModel.followAuth(videoBean.getAuthname());
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatroomManager().leaveChatRoom(Constant.ROOM_ID);
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener);
    }
}